import React, { useState, useEffect } from 'react';
import { Table, Input, Switch, Divider, Button, message, Modal, Space, Drawer, Tree, Spin } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, SearchOutlined } from '@ant-design/icons';
import { positionpage, positionDelete, positionUpdateStatus } from '@/services/system/postmanagement';
import { useNavigate, useModel } from 'umi';
import { useOutletContext } from '@umijs/max';
import AuthorizedButton from '@/components/AuthorizedButton';
import CustomPageContainer from '@/components/CustomPageContainer';
import type { DataNode } from 'antd/es/tree';
import { getresource, getAllResourceList ,getAlreadyAllocationResourceIds,resourceAllocation} from '@/services/ant-design-pro/api';

// 定义岗位类型接口
interface PositionType {
  id: string;
  positionId: string;
  institutionId: string;
  positionName: string;
  sort: number;
  status: number;
  createTime: number;
  updateTime: number;
  createUser: string;
  updateUser: string;
  departmentId?: string;
}

interface ButtonData {
  id: string;
  pageId: string;
  resourceName: string;
  icon?: string;
  action: string;
}

const PostManagement: React.FC = () => {
  const [positions, setPositions] = useState<PositionType[]>([]);
  const { buttonData } = useOutletContext<{ buttonData: ButtonData[] }>();
  console.log('buttonData>>', buttonData);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchText, setSearchText] = useState('');
  const navigate = useNavigate();
  const { institutionId, institutionRoleId, departmentId, positionId } = useModel('auth');
  // 权限分配相关状态
  const [permissionDrawerVisible, setPermissionDrawerVisible] = useState(false);
  const [permissionLoading, setPermissionLoading] = useState(false);
  const [permissionTree, setPermissionTree] = useState<DataNode[]>([]);
  // 添加原始资源数据状态
  const [originalResourceData, setOriginalResourceData] = useState<any[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [halfCheckedKeys, setHalfCheckedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [currentRecord, setCurrentRecord] = useState<PositionType | null>(null);
  // 重新命名变量以更清晰地表示其含义：是否显示按钮类型的权限
  const [showButtonResource, setShowButtonResource] = useState(false);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async (params: Record<string, any> = {}) => {
    try {
      const response = await positionpage({
        current: params?.current || 1,
        size: params?.pageSize || 10,
        institutionId,
        institutionRoleId,
        ...params
      });

      if (response.code === 200) {
        setPositions(response.data);
        setPagination({
          current: response.data.current,
          pageSize: response.data.size,
          total: response.data.total,
        });
      }
    } catch (error) {
      console.error(error);
    }
  };

  const columns = [
    {
      title: '岗位名称',
      dataIndex: 'positionName',
      key: 'positionName',
      width: 180,
    },
    {
      title: '岗位编号',
      dataIndex: 'positionId',
      key: 'positionId',
      width: 150,
    },
    {
      title: '岗位排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 100,
    },
    {
      title: '创建人',
      dataIndex: 'createUser',
      key: 'createUser',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      render: (time: number) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '修改人',
      dataIndex: 'updateUser',
      key: 'updateUser',
      width: 120,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 180,
      render: (time: number) => time ? new Date(time).toLocaleString() : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: number, record: PositionType) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={status === 0}
          onChange={(checked) => handleStatusChange(record, checked)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_: any, record: PositionType) => (
        <span>
          <Space split={<Divider type="vertical" />}>
            <AuthorizedButton
              buttonData={buttonData}
              action="edit"
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              编辑
            </AuthorizedButton>
            <AuthorizedButton
              buttonData={buttonData}
              action="delete"
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              删除
            </AuthorizedButton>
            <AuthorizedButton
              buttonData={buttonData}
              action="view"
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleView(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              详情
            </AuthorizedButton>
            <AuthorizedButton
              buttonData={buttonData}
              action="allow"
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleAssignPermission(record)}
              style={{
                padding: 0,
                height: '22px',
                lineHeight: '22px',
              }}
            >
              分配权限
            </AuthorizedButton>
          </Space>
        </span>
      ),
    },
  ];

  const handleAdd = () => {
    navigate('/system/postmanagement/add');
  };

  const handleEdit = (record: PositionType) => {
    navigate('/system/postmanagement/edit', {
      state: { record }
    });
  };

  const handleDelete = (record: PositionType) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除岗位 "${record.positionName}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await positionDelete({
            positionId: record.positionId,
            institutionId,
            institutionRoleId,
          });

          if (response.code === 200) {
            message.success('删除成功');
            fetchData();
          } else {
            message.error(response.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      }
    });
  };

  const handleView = (record: PositionType) => {
    navigate('/system/postmanagement/view', {
      state: { record }
    });
  };

  const handleStatusChange = async (record: PositionType, checked: boolean) => {
    try {
      const response = await positionUpdateStatus({
        ...record,
        status: checked ? 0 : 1
      });

      if (response.code === 200) {
        message.success('状态更新成功');
        fetchData();
      } else {
        message.error(response.msg || '状态更新失败');
        fetchData();
      }
    } catch (error) {
      console.error('状态更新失败:', error);
      message.error('状态更新失败');
      fetchData();
    }
  };

  // 搜索处理函数
  const handleSearch = (value: string) => {
    setSearchText(value);
    fetchData({ positionName: value });
  };

  // 打开权限分配抽屉
  const handleAssignPermission = (record: PositionType) => {
    setCurrentRecord(record);
    setPermissionDrawerVisible(true);
    fetchPermissionTree(record);
  };

  // 关闭权限分配抽屉
  const handlePermissionDrawerClose = () => {
    setPermissionDrawerVisible(false);
    setCurrentRecord(null);
  };

  // 将API返回的数据处理成Tree需要的格式，并根据showButtonResource过滤按钮节点
  const processResourceData = (apiData: any[], showButtons: boolean): DataNode[] => {
    // 递归函数来处理树形结构
    const processNode = (node: any): DataNode | null => {
      // 如果是按钮类型且不显示按钮，则跳过此节点
      if (node.resourceType === 'button' && !showButtons) {
        return null;
      }

      // 处理子节点
      let children: DataNode[] | undefined = undefined;
      if (node.children && node.children.length > 0) {
        // 递归处理子节点并过滤掉null结果
        const processedChildren = node.children
          .map(processNode)
          .filter((child: DataNode | null): child is DataNode => child !== null);

        if (processedChildren.length > 0) {
          children = processedChildren;
        }
      }

      // 返回处理后的节点
      return {
        title: (
          <span>
            {node.resourceName}
            {node.resourceType === 'button' && (
              <span style={{ color: '#52c41a', marginLeft: '8px', fontSize: '12px' }}>
                [按钮]
              </span>
            )}
            {node.resourceType === 'menu' && (
              <span style={{ color: '#1890ff', marginLeft: '8px', fontSize: '12px' }}>
                [菜单]
              </span>
            )}
            {node.resourceType === 'page' && (
              <span style={{ color: '#722ed1', marginLeft: '8px', fontSize: '12px' }}>
                [页面]
              </span>
            )}
          </span>
        ),
        key: node.resourceId,
        children,
        // resourceType不是DataNode的标准属性，我们可以使用自定义属性来存储，但要明确声明类型
        isLeaf: node.resourceType === 'button',
        // 使用data字段来存储额外信息
        data: { resourceType: node.resourceType }
      } as DataNode;
    };

    // 处理每个顶级节点
    return apiData
      .map(processNode)
      .filter((node: DataNode | null): node is DataNode => node !== null);
  };

  // 获取权限树数据
  const fetchPermissionTree = async (record: PositionType) => {
    try {
      setPermissionLoading(true);

      const response = await getAllResourceList({
        institutionId,
        departmentId,
        positionId,
        institutionRoleId,
      });
      console.log('资源树数据:', response);

      if (response.code === 200 && response.data) {
        // 保存原始数据
        setOriginalResourceData(response.data);

        // 处理数据并根据当前showButtonResource状态过滤按钮
        const treeData = processResourceData(response.data, showButtonResource);
        setPermissionTree(treeData);

        // 获取已分配的权限
        const assignedResponse = await getAlreadyAllocationResourceIds({
          institutionId,
          positionId: record?.positionId,
          institutionRoleId,
          departmentId: record?.departmentId,
        });
        console.log('已分配的权限:', assignedResponse);
        // 确保返回的是字符串数组类型的ID
        const assignedIds = assignedResponse.data && Array.isArray(assignedResponse.data)
          ? assignedResponse.data.map((item: any) => typeof item === 'string' ? item : String(item.id || item.resourceId || item))
          : [];
        console.log('已分配的权限IDs:', assignedIds);
        setCheckedKeys(assignedIds);

        // 默认展开所有一级菜单
        const expandKeys = response.data.map((item: any) => item.resourceId);
        setExpandedKeys(expandKeys);
      } else {
        message.error(response.msg || '获取权限数据失败');
      }
    } catch (error) {
      console.error('获取权限数据失败:', error);
      message.error('获取权限数据失败');
    } finally {
      setPermissionLoading(false);
    }
  };

  // 处理权限勾选
  const onCheckPermission = (
    checked: { checked: React.Key[]; halfChecked: React.Key[] } | React.Key[]
  ) => {
    if (Array.isArray(checked)) {
      // 如果是简单数组，则直接设置选中的键
      setCheckedKeys(checked);
      setHalfCheckedKeys([]);
    } else {
      // 如果是对象，则分别设置完全选中和半选中的键
      setCheckedKeys(checked.checked);
      setHalfCheckedKeys(checked.halfChecked);
    }
  };

  // 保存权限分配
  const handleSavePermissions = async () => {
    if (!currentRecord) return;

    try {
      setPermissionLoading(true);

      // 提交当前选中的keys
      console.log('提交的权限IDs:', checkedKeys);

      // 确保以正确的数组格式提交，避免resourceIdList[]形式的参数
      const requestData = {
        resourceIdList: checkedKeys, // 传递一个数组对象
        institutionId,
        positionId: currentRecord?.positionId,
        institutionRoleId,
      };

      // 如果存在departmentId则添加
      if (currentRecord.departmentId) {
        // @ts-ignore - 临时忽略类型检查，因为我们已经在接口中添加了可选字段
        requestData.departmentId = currentRecord.departmentId;
      }

      const response = await resourceAllocation(requestData);
      console.log('保存权限:', response);

      if (response.code === 200) {
        message.success(`岗位 "${currentRecord.positionName}" 权限分配成功`);
        setPermissionDrawerVisible(false);
        setCurrentRecord(null);
      } else {
        message.error(response.msg || '权限分配失败');
      }
    } catch (error) {
      console.error('保存权限失败:', error);
      message.error('保存权限失败');
    } finally {
      setPermissionLoading(false);
    }
  };

  // 处理树展开/收起
  const onExpandPermission = (expandedKeys: React.Key[]) => {
    setExpandedKeys(expandedKeys);
  };

  return (
    <div style={{ background: '#f0f2f5', minHeight: '100vh' }}>
      <CustomPageContainer style={{ background: '#fff', borderRadius: '8px', padding: '24px', margin: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <AuthorizedButton
            buttonData={buttonData}
            action="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增
          </AuthorizedButton>
          <div style={{ width: '300px' }}>
            <Input
              placeholder="请输入岗位名称进行搜索"
              value={searchText}
              onChange={e => handleSearch(e.target.value)}
              suffix={<SearchOutlined style={{ color: '#1890ff' }} />}
              style={{
                borderRadius: '20px',
                backgroundColor: '#f5f5f5',
                border: 'none',
                padding: '8px 16px'
              }}
            />
          </div>
        </div>
        <Table
          columns={columns}
          dataSource={positions}
          rowKey="id"
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              fetchData({ current: page, size: pageSize });
            },
          }}
          scroll={{ x: 1300 }}
        />

        {/* 权限分配抽屉 */}
        <Drawer
          title={`分配权限: ${currentRecord?.positionName || ''}`}
          width={500}
          open={permissionDrawerVisible}
          onClose={handlePermissionDrawerClose}
          maskClosable={false}
          destroyOnClose={true}
          footer={
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button onClick={handlePermissionDrawerClose} style={{ marginRight: 8 }}>
                取消
              </Button>
              <Button
                type="primary"
                onClick={handleSavePermissions}
                loading={permissionLoading}
              >
                保存
              </Button>
            </div>
          }
        >
          <Spin spinning={permissionLoading}>
            <div style={{ marginBottom: '16px' }}>
              <div style={{ marginBottom: '8px' }}>
                <strong>岗位名称:</strong> {currentRecord?.positionName || '-'}
              </div>
              <div style={{ marginBottom: '8px' }}>
                <strong>岗位编号:</strong> {currentRecord?.positionId || '-'}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                <p>请选择要分配给该岗位的权限资源：</p>
                <Switch
                  checkedChildren="显示按钮"
                  unCheckedChildren="隐藏按钮"
                  checked={showButtonResource}
                  onChange={(checked) => {
                    setShowButtonResource(checked);
                    // 使用已保存的原始数据重新生成树
                    if (originalResourceData.length > 0) {
                      setPermissionLoading(true);
                      // 短暂延迟以显示加载状态
                      setTimeout(() => {
                        const treeData = processResourceData(originalResourceData, checked);
                        setPermissionTree(treeData);
                        setPermissionLoading(false);
                      }, 300);
                    }
                  }}
                  style={{ marginLeft: '10px' }}
                />
              </div>
            </div>

            <Tree
              checkable
              checkedKeys={checkedKeys}
              onCheck={onCheckPermission}
              expandedKeys={expandedKeys}
              onExpand={onExpandPermission}
              treeData={permissionTree}
              height={500}
              fieldNames={{
                title: 'title',
                key: 'key',
                children: 'children'
              }}
              // 添加checkStrictly属性，使父子节点选中状态不再关联
              checkStrictly={true}
            />
          </Spin>
        </Drawer>
      </CustomPageContainer>
    </div>
  );
};

export default PostManagement;
